package com.jk.garden1.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jk.garden1.dao.EsStaffDao;
import com.jk.garden1.dao.StaffDao;
import com.jk.garden1.entity.BuildingEntity;
import com.jk.garden1.entity.StaffEntity;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * 员工信息
 */
@Service
public class StaffService {
    @Autowired
    private StaffDao staffDao;
    @Autowired
    private ElasticsearchRestTemplate es;
    @Autowired
    private EsStaffDao esStaffDao;

    //定义验证码
    public static String charactercode = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";




    /**
     * 查询全部
     */
    public List<StaffEntity> selectStaffList() {
        return staffDao.selectList(null);
    }
    /**
     * 添加员工
     */
    public void addStaff(StaffEntity staffEntity) {
        StringBuilder stringBuilder = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 14; i++) {
            stringBuilder.append(charactercode.charAt(random.nextInt(14)));
        }
        staffEntity.setStaffcard(stringBuilder.toString());
        staffEntity.setStaffstate("正常");
        staffDao.insert(staffEntity);
    }
    /**
     * 注销
     * @param id
     */
    public void updateById(Integer id) {
        StaffEntity staffEntity = staffDao.selectById(id);
        staffEntity.setStaffstate("已注销");
        staffDao.updateById(staffEntity);
    }

    /**
     * 删除
     * @param id
     */
    public void delById(Integer id) {
        staffDao.deleteById(id);
    }


    /**
     * 新建索引
     */
    public void create(){
        es.createIndex(StaffEntity.class);
        QueryWrapper wp=new QueryWrapper();
        List<StaffEntity> list = staffDao.selectList(wp);
        list.forEach(a -> {
            esStaffDao.save(a);
        });
    }

    /**
     * es高亮
     * @param staff
     * @return
     */
    public List<StaffEntity> queryEsList(StaffEntity staff) {
        if (es.indexExists(StaffEntity.class)){
            create();
        }
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        //手机号精确查
        if(StringUtils.hasText(staff.getPhone())){
            nativeSearchQueryBuilder.withQuery(QueryBuilders.termQuery("phone",staff.getPhone()));
        }
        //公司名称模糊查
        if(StringUtils.hasText(staff.getCompanyname())){
            nativeSearchQueryBuilder.withQuery(QueryBuilders.matchQuery("companyname",staff.getCompanyname()));
        }
        //姓名模糊查
        if(StringUtils.hasText(staff.getName())){
            nativeSearchQueryBuilder.withQuery(QueryBuilders.matchQuery("name",staff.getName()))
                    .withHighlightFields(new HighlightBuilder.Field("name").preTags("<font color='red'>").postTags("</font>"));
        }
        SearchQuery build = nativeSearchQueryBuilder.build();
        if(StringUtils.hasText(staff.getName())){
            AggregatedPage<StaffEntity> employeeEntity = es.queryForPage(build, StaffEntity.class, new SearchResultMapper() {
                @Override
                public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
                    SearchHits hits = searchResponse.getHits();
                    List list = new ArrayList();
                    for (SearchHit hit : hits) {
                        Map<String, Object> sourceAsMap = hit.getSourceAsMap();
                        Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                        sourceAsMap.put("name", highlightFields.get("name").getFragments()[0].toString());
                        list.add(sourceAsMap);
                    }
                    return new AggregatedPageImpl<>(list);
                }
                @Override
                public <T> T mapSearchHit(SearchHit searchHit, Class<T> aClass) {
                    return null;
                }
            });
            return employeeEntity.getContent();
        }else{
            List<StaffEntity> list2 = es.queryForList(build, StaffEntity.class);
            return  list2;
        }
    }

    /**
     * 查询员工
     */
    public Object selectname(String name) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("name",name);
        return staffDao.selectList(wrapper);
    }
}
